'use client';

import React from 'react';
import { Check, ChevronDown, Network } from 'lucide-react';
import { useChain } from '@/context/ChainContext';
import { getAllChains, ChainType } from '@/config/chains';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

interface ChainSelectorProps {
  className?: string;
  showLabel?: boolean;
}

export const ChainSelector: React.FC<ChainSelectorProps> = ({
  className = '',
  showLabel = true,
}) => {
  const { currentChain, chainConfig, switchChain } = useChain();
  const allChains = getAllChains();

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          className={`justify-between ${className}`}
        >
          <div className="flex items-center space-x-2">
            <Network className="h-4 w-4" />
            <span className={`${chainConfig.isTestnet ? 'text-orange-600' : 'text-green-600'}`}>
              {showLabel ? chainConfig.displayName : chainConfig.name}
            </span>
          </div>
          <ChevronDown className="h-4 w-4 opacity-50" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-48">
        {allChains.map((chain) => (
          <DropdownMenuItem
            key={chain.id}
            onClick={() => switchChain(chain.id as ChainType)}
            className="flex items-center justify-between cursor-pointer"
          >
            <div className="flex items-center space-x-2">
              <div
                className={`w-2 h-2 rounded-full ${
                  chain.isTestnet ? 'bg-orange-500' : 'bg-green-500'
                }`}
              />
              <span>{chain.displayName}</span>
            </div>
            {currentChain === chain.id && (
              <Check className="h-4 w-4 text-green-600" />
            )}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};